﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using eLearning.Model;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using eLearning.Util;

namespace eLearning.DosenView
{
    public partial class QuestionQuizPage : PhoneApplicationPage
    {
        private QuestionList listSoal;
        private Question selectedSoal;
        private Quiz quiz;

        public QuestionQuizPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.QUIZ))
            {
                quiz = (Quiz)PhoneApplicationService.Current.State[Config.QUIZ];
                pivotHeader.Header = "Soal " + quiz.Nama;
            }

            LoadQuestionList(quiz);
            ManageButton(selectedSoal);
        }

        private void LoadQuestionList(Quiz quiz)
        {
            string url = string.Format("{0}&{1}", Config.Instance.QUESTION_SERVICE_URL() + "?action=viewSQ", Guid.NewGuid().ToString());
            string json = JsonConvert.SerializeObject(quiz);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listQuestion_UploadStringCompleted);
            try
            {
                webClient.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void listQuestion_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                int noUrut = 1;
                listQuestion.Items.Clear();
                listSoal = JsonConvert.DeserializeObject<QuestionList>(e.Result);
                foreach (Question ques in listSoal)
                {
                    ques.NoUrut = Convert.ToString(noUrut + ".");
                    listQuestion.Items.Add(ques);
                    noUrut++;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SaveQuestion(Question data)
        {
            string json = null, url = null;

            if (data.Id == null)
            {
                url = Config.Instance.QUESTION_SERVICE_URL() + "?action=addSQ"; //create
            }
            else
            {
                url = Config.Instance.QUESTION_SERVICE_URL() + Config.UPDATE_ACTION_KEY; //update
            }
            json = JsonConvert.SerializeObject(data);


            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(saveChange_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void saveChange_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(e.Result))
                {
                    if (!e.Result.Contains("Success"))
                        selectedSoal.Id = e.Result;
                    MessageBox.Show("Data Saved.");
                }
                else
                {
                    MessageBox.Show("ERROR : " + e.Result);
                }
                LoadQuestionList(quiz);
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void RemoveCurrentQuestion()
        {
            string json = null, url = null;

            if (selectedSoal != null)
            {
                url = Config.Instance.QUESTION_SERVICE_URL() + Config.REMOVE_ACTION_KEY;
                json = JsonConvert.SerializeObject(selectedSoal);

                Uri uri = new Uri(url, UriKind.Absolute);
                WebClient client = new WebClient();

                client.Encoding = Encoding.UTF8;
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

                client.UploadStringCompleted += new UploadStringCompletedEventHandler(removeQuestion_UploadStringCompleted);

                try
                {
                    client.UploadStringAsync(uri, "POST", json);
                }
                catch (Exception) { }
            }
        }

        private void removeQuestion_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                MessageBox.Show("Message : " + e.Result);
                if (e.Result.Contains("Success"))
                    LoadQuestionList(quiz);

                createNewPertanyaan();
                selectedSoal = new Question();

                pivotQuestion.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void listQuiz_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                selectedSoal = (Question)e.AddedItems[0];

                textBoxPertanyaan.Text = selectedSoal.Pertanyaan;
                textBoxPilihanA.Text = selectedSoal.PilihanA;
                textBoxPilihanB.Text = selectedSoal.PilihanB;
                textBoxPilihanC.Text = selectedSoal.PilihanC;
                textBoxPilihanD.Text = selectedSoal.PilihanD;
                setSelectedJawaban(selectedSoal.Jawaban);

                pivotQuestion.SelectedIndex = 1;
                ((ListBox)sender).SelectedIndex = -1;
            }
        }

        private void addButton_Click(object sender, System.EventArgs e)
        {
            createNewPertanyaan();
            selectedSoal = new Question();

            pivotQuestion.SelectedIndex = 1;
        }

        private void saveButton_Click(object sender, System.EventArgs e)
        {

            if (string.IsNullOrEmpty(textBoxPertanyaan.Text))
            {
                MessageBox.Show("Pertanyaan tidak boleh kosong!");
                return;
            } if (string.IsNullOrEmpty(textBoxPilihanA.Text))
            {
                MessageBox.Show("Pilihan A tidak boleh kosong!");
                return;
            } if (string.IsNullOrEmpty(textBoxPilihanB.Text))
            {
                MessageBox.Show("Pilihan B tidak boleh kosong!");
                return;
            } if (string.IsNullOrEmpty(textBoxPilihanC.Text))
            {
                MessageBox.Show("Pilihan C tidak boleh kosong!");
                return;
            } if (string.IsNullOrEmpty(textBoxPilihanD.Text))
            {
                MessageBox.Show("Pilihan D tidak boleh kosong!");
                return;
            } if (getSelectedJawaban() == Jawaban.None)
            {
                MessageBox.Show("Jawaban yang benar belum dipilih!");
                return;
            }
            selectedSoal.Quis = quiz;
            selectedSoal.Pertanyaan = textBoxPertanyaan.Text;
            selectedSoal.PilihanA = textBoxPilihanA.Text;
            selectedSoal.PilihanB = textBoxPilihanB.Text;
            selectedSoal.PilihanC = textBoxPilihanC.Text;
            selectedSoal.PilihanD = textBoxPilihanD.Text;
            selectedSoal.Jawaban = getSelectedJawaban();

            SaveQuestion(selectedSoal);
        }

        private void removeButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Remove " + Utility.subString(selectedSoal.Pertanyaan, 0, 20) + "?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                RemoveCurrentQuestion();
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            LoadQuestionList(quiz);
            ManageButton(selectedSoal);
            pivotQuestion.SelectedIndex = 0;

            createNewPertanyaan();
            selectedSoal = new Question();
        }

        private void ManageButton(Question soal)
        {
            if (soal != null && pivotQuestion.SelectedIndex == 1)
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = true;
            }
            else
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = false;
            }

            if (pivotQuestion.SelectedIndex == 0)
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[3]).IconUri = new Uri("/Images/refresh.png", UriKind.RelativeOrAbsolute);
                ((ApplicationBarIconButton)ApplicationBar.Buttons[3]).Text = "Refresh";
            }
            else
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[3]).IconUri = new Uri("/Images/undo.png", UriKind.RelativeOrAbsolute);
                ((ApplicationBarIconButton)ApplicationBar.Buttons[3]).Text = "Cancel";
            }
        }

        private void pivotQuestion_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ManageButton(selectedSoal);
        }

        private void createNewPertanyaan()
        {
            textBoxPertanyaan.Text = "";
            textBoxPilihanA.Text = "";
            textBoxPilihanB.Text = "";
            textBoxPilihanC.Text = "";
            textBoxPilihanD.Text = "";
            setSelectedJawaban(Jawaban.None);
        }

        private Jawaban getSelectedJawaban()
        {
            if (radioButtonA.IsChecked.Value)
                return Jawaban.A;
            else if (radioButtonB.IsChecked.Value)
                return Jawaban.B;
            else if (radioButtonC.IsChecked.Value)
                return Jawaban.C;
            else if (radioButtonD.IsChecked.Value)
                return Jawaban.D;
            else
                return Jawaban.None;
        }

        private void setSelectedJawaban(Jawaban jawaban)
        {
            if (jawaban == Jawaban.A)
                radioButtonA.IsChecked = true;
            else if (jawaban == Jawaban.B)
                radioButtonB.IsChecked = true;
            else if (jawaban == Jawaban.C)
                radioButtonC.IsChecked = true;
            else if (jawaban == Jawaban.D)
                radioButtonD.IsChecked = true;
            else
            {
                radioButtonA.IsChecked = false;
                radioButtonB.IsChecked = false;
                radioButtonC.IsChecked = false;
                radioButtonD.IsChecked = false;
            }
        }

        private void menuQuestion_Click(object sender, EventArgs e)
        {
            Utility.GotoPage(this, "/View/Dosen/QuestionSelectPage.xaml");
            PhoneApplicationService.Current.State[Config.QUIZ] = quiz;
        }

    }
}